package top.kaoshanji.p1ch11a;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch11a-374页a：后端搜索引擎
 * URL访问地址：/searchLogic
 * @author kaoshanji
 * ^_^
 * create time 2025/4/5 15:32
 */
public class SearchLogic extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 取得搜索字符
        String search = req.getParameter("search");

        // 计算包括字符串的URL
        String[] results = getResults(search);

        // 以请求属性指定结果...把字符串数组放进去了
        req.setAttribute("results", results);

        // 发送到显示页
        String display = "/searchView";
        RequestDispatcher dispatcher = req.getRequestDispatcher(display);
        dispatcher.forward(req, resp);

    }

    // 使用这个方法将调用真正的搜索引擎逻辑并返回关于结果的URL以外的信息
    String[] getResults(String search) {
        return new String[] { "http://www.abc.com",
                "http://www.xyz.com" };
    }

}
